/*
 * UserService.java
 *
 * Copyright 2012 the original author or authors(ninglong).
 *
 * Licensed under the web-geek, Version 1.0 (the "License");
 *
 */
package org.geek.user.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.geek.common.entity.Criteria;
import org.geek.domain.User;
import org.geek.user.mapper.UserMapper;
import org.geek.user.service.IUserService;
import org.springframework.stereotype.Service;

/**   
 * <p>用户服务类</p>
 * @author ninglong bhd2973@qq.com   
 * @version V1.0   
 */
@Service
public class UserService implements IUserService {
	
	@Resource
	private UserMapper userMapper;

	public User getUserByAccount(String account) {
		return userMapper.getUserByAccount(account);
	}

	public List<User> getUserByCriteria(Criteria criteria) {
		return userMapper.getUserByCriteria(criteria);
	}

	public int countUserByCriteria(Criteria criteria) {
		return userMapper.countUserByCriteria(criteria);
	}

	public int addUser(User user) {
		return userMapper.addUser(user);
	}
	
	public int modUser(User user) {
		return userMapper.modUser(user);
	}
	
	public int delUserByUserId(int userId) {
		int i = userMapper.delUserByUserId(userId);
		i = i + userMapper.delUserAndRoleByUserId(userId);//删除用户后，将t_user_role表与该用户有关的数据删除
		return i;
	}

	@Override
	public int saveRole2User(int userId,String [] roleIds) {
		if(roleIds == null){
			userMapper.delRole2UserByUserId(userId);
			return 1;
		}
		int i = 0;
		if(userMapper.delRole2UserByUserId(userId)>=0){//先删除旧的角色
			//添加新的
			Criteria criteria = new Criteria();
			criteria.put("userId", userId);
			for(String roleId:roleIds){
				criteria.put("roleId", Integer.valueOf(roleId));
				i = i+userMapper.saveRole2User(criteria);
			}
		}
		return i;
	}

	@Override
	public int saveGroup2User(int userId,String [] groupIds) {
		if(groupIds == null){
			userMapper.delGroup2UserByUserId(userId);
			return 1;
		}
		int i = 0;
		if(userMapper.delGroup2UserByUserId(userId)>=0){//先删除旧的组
			//添加新的
			Criteria criteria = new Criteria();
			criteria.put("userId", userId);
			for(String groupId:groupIds){
				criteria.put("groupId", groupId);
				i = i+userMapper.saveGroup2User(criteria);
			}
		}
		return i;
	}
}
